<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import TableLayout from '@/layout/table-layout.vue';
  import { usePageTable } from '@/hooks/arco/usePageTable';
  import { useForm } from '@/hooks/arco/useForm';
  import DetailDrawer from '@/components/detail-drawer/index.vue';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import useDetailDrawerBinder from '@/hooks/arco/useDetailDrawerBinder';
  import {
    queryRecords,
    createRecord,
    deleteRecord,
    queryProducts,
  } from '@/api/reemployment-management/record';
  import { queryUnits } from '@/api/reemployment-management/product';
  import { getLabelFromOptions } from '@/views/lhj-v1/util';

  const loading = ref(false);
  const baseNameMap = {
    itemId: { key: 'productId', label: '记录ID' },
    itemDate: {
      key: 'productDate',
      label: '生产日期',
      placeholder: '请选择生产日期',
    },
    itemDateRange: {
      key: 'dateRange',
      label: '生产日期',
      placeholder: ['请选择开始日期', '请选择结束日期'],
    },
    itemProject: {
      key: 'productName',
      label: '项目名称',
      placeholder: '请输入项目名称',
    },
    formProject: {
      key: 'productName',
      label: '生产项目',
      placeholder: '请选择生产项目',
    },
    itemPerson: {
      key: 'producter',
      label: '生产人员',
      placeholder: '请输入生产人员',
    },
    itemUnit: {
      key: 'unitCode',
      label: '计量单位',
      placeholder: '请选择计量单位',
    },
    itemUnitName: {
      key: 'productUnit',
      label: '计量单位',
      placeholder: '请选择计量单位',
    },
    itemPrice: { key: 'price', label: '单价（元）', placeholder: '请输入单价' },
    formPrice: { key: 'productPrice', label: '单价（元）' },
    formYield: {
      key: 'productStock',
      label: '生产产量',
      placeholder: '请输入生产',
    },
    itemYield: {
      key: 'stock',
      label: '生产产量',
      placeholder: '请输入生产产量',
    },
    itemTotalPrice: { key: 'totalAmount', label: '合计金额（元）' },
    itemPlace: {
      key: 'address',
      label: '生产地点',
      placeholder: '请输入生产地点',
    },
    btnActionTitle: { label: '操作' },
    btnAction: { label: '删除' },
  };

  const dataPage = ref({
    total: 0,
    page: 1,
    pageSize: 10,
  });

  // 查询表格列配置
  const tableColumns = [
    {
      title: baseNameMap.itemId.label,
      dataIndex: baseNameMap.itemId.key,
      // width: 120,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: baseNameMap.itemDate.label,
      dataIndex: baseNameMap.itemDate.key,
      // width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: baseNameMap.formProject.label,
      dataIndex: baseNameMap.formProject.key,
      // width: 180,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: baseNameMap.itemPerson.label,
      dataIndex: baseNameMap.itemPerson.key,
      // width: 160,
    },
    {
      title: baseNameMap.itemUnitName.label,
      dataIndex: baseNameMap.itemUnitName.key,
      // width: 120,
    },
    {
      title: baseNameMap.formPrice.label,
      dataIndex: baseNameMap.formPrice.key,
      // width: 120,
    },
    {
      title: baseNameMap.formYield.label,
      dataIndex: baseNameMap.formYield.key,
      // width: 120,
    },
    {
      title: baseNameMap.itemTotalPrice.label,
      dataIndex: baseNameMap.itemTotalPrice.key,
      // width: 160,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: baseNameMap.itemPlace.label,
      dataIndex: baseNameMap.itemPlace.key,
      // width: 160,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: baseNameMap.btnActionTitle.label,
      align: 'center' as const,
      dataIndex: 'action',
      slotName: 'action',
      fixed: 'right',
      width: 100,
    },
  ];

  // const unitOptions = useSelectOption({
  //   apiFun: queryUnits,
  //   fieldNames: {
  //     label: 'name',
  //     value: 'code',
  //   },
  // });
  const productOptions = useSelectOption({
    apiFun: queryProducts,
    fieldNames: {
      label: 'name',
      value: 'id',
      unitCode: 'unitCode',
      unitName: 'unitName',
      price: 'price',
    },
  });
  const unitOptions = ref<any[]>([]);

  const currentProject = ref<any>({});
  const pageTable = usePageTable({
    resetBtn: false,
    searchForm: {
      state: {
        [baseNameMap.itemProject.key]: '',
        [baseNameMap.itemPerson.key]: '',
        [baseNameMap.itemDateRange.key]: [],
      },
    },
    table: {
      rowKey: baseNameMap.itemId.key,
      fakePage: true,
      apiFun: async (query) => {
        return new Promise((resolve) => {
          let itemTimeStart = '';
          let itemTimeEnd = '';
          if (query[baseNameMap.itemDateRange.key]) {
            const itemDateRange: string[] = Array.from(
              query[baseNameMap.itemDateRange.key]
            );
            if (itemDateRange.length >= 2) {
              [itemTimeStart, itemTimeEnd] = itemDateRange;
            }
          }
          const params = {
            pageNum: dataPage.value.page,
            pageSize: dataPage.value.pageSize,
            [baseNameMap.itemProject.key]: query[baseNameMap.itemProject.key],
            [baseNameMap.itemPerson.key]: query[baseNameMap.itemPerson.key],
            startDate: itemTimeStart,
            endDate: itemTimeEnd,
          };
          // resolve([]);
          queryRecords(params)
            .then((res) => {
              dataPage.value.total = res.total;
              resolve(res.list);
            })
            .catch((err) => {})
            .finally(() => {});
        });
      },
      onSuccess(data) {
        // dataDepartments.value = getDepartmentList(data);
      },
      columns: tableColumns,
    },
  });

  const currentItem = useForm({
    state: {
      [baseNameMap.itemId.key]: '',
      [baseNameMap.formProject.key]: '',
      [baseNameMap.itemUnit.key]: '',
      [baseNameMap.itemPrice.key]: 0,
      [baseNameMap.itemYield.key]: 0,
      [baseNameMap.itemPerson.key]: '',
      [baseNameMap.itemPlace.key]: '',
      [baseNameMap.itemDate.key]: '',
    },
    rules: {
      [baseNameMap.formProject.key]: {
        required: true,
        message: baseNameMap.formProject.placeholder,
      },
      [baseNameMap.itemUnit.key]: {
        required: true,
        message: baseNameMap.itemUnit.placeholder,
      },
      [baseNameMap.itemPrice.key]: {
        required: true,
        message: baseNameMap.itemPrice.placeholder,
      },
    },
  });

  const detailDrawerHandler = useDetailDrawerBinder({
    modes: ['detail', 'add', 'edit'] as const,
    renderTitle: (mode) => (mode === 'add' ? '新增记录' : '项目详情'),
    modalName: '项目',
    deleteText: '提示：此操作不可逆，删除后将无法恢复。',
    onShow(mode, otherParams) {
      if (mode === 'add') {
        currentItem.backToInit();
        currentProject.value = {};
      } else {
        currentItem.setFieldsValue(otherParams);
      }
    },
    async onOkClick(mode) {
      await currentItem.validate();
      loading.value = true;
      const data = {
        [baseNameMap.itemId.key]: currentItem.state[baseNameMap.itemId.key],
        [baseNameMap.itemDate.key]: currentItem.state[baseNameMap.itemDate.key],
        [baseNameMap.itemPerson.key]:
          currentItem.state[baseNameMap.itemPerson.key],
        [baseNameMap.itemYield.key]:
          currentItem.state[baseNameMap.itemYield.key],
        [baseNameMap.itemPlace.key]:
          currentItem.state[baseNameMap.itemPlace.key],
        //
        [baseNameMap.itemUnit.key]: currentItem.state[baseNameMap.itemUnit.key],
        [baseNameMap.itemPrice.key]:
          currentItem.state[baseNameMap.itemPrice.key],
      };
      if (mode === 'add') {
        return createRecord(data);
      }
      return Promise.resolve(null);
    },
    deleteApi: () => {
      loading.value = true;
      return deleteRecord(currentItem.state[baseNameMap.itemId.key] as string);
    },
    onHide(mode) {
      if (loading.value) {
        pageTable.reload();
        loading.value = false;
      }
    },
  });

  const handleDeleteRecord = (item: any) => {
    deleteRecord(item.id)
      .then((res) => {
        Message.success(res);
        pageTable.reload();
      })
      .catch((err) => {})
      .finally(() => {
        loading.value = false;
      });
  };

  watch(()=>currentItem.state[baseNameMap.itemId.key], (newVal)=>{
    productOptions.bindProps.options.forEach((project: any)=>{
      if (newVal === project.value) {
        // console.log('current project:', project);
        currentProject.value = project;
        currentProject.value.price = parseFloat(project.price);
        unitOptions.value = [{
          value: project.unitCode,
          label: project.unitName,
        }];
      }
    });
  });
</script>

<template>
  <div class="m-record">
    <TableLayout
      v-bind="pageTable.bindProps"
      @create="detailDrawerHandler.showModal('add')"
    >
      <template #searchForm="{ state }">
        <!-- 项目名称 -->
        <a-form-item
          :field="baseNameMap.itemProject.key"
          :label="baseNameMap.itemProject.label"
        >
          <a-input
            v-model="state[baseNameMap.itemProject.key]"
            :placeholder="baseNameMap.itemProject.placeholder"
            allow-clear
          />
        </a-form-item>
        <!-- 生产人员 -->
        <a-form-item
          :field="baseNameMap.itemPerson.key"
          :label="baseNameMap.itemPerson.label"
        >
          <a-input
            v-model="state[baseNameMap.itemPerson.key]"
            :placeholder="baseNameMap.itemPerson.placeholder"
            allow-clear
          />
        </a-form-item>
        <!-- 生产时间 -->
        <a-form-item
          :field="baseNameMap.itemDate.key"
          :label="baseNameMap.itemDate.label"
        >
          <a-range-picker
            v-model="state[baseNameMap.itemDateRange.key]"
            style="width: 100%"
          />
        </a-form-item>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-popconfirm
            content="确定删除此记录吗？"
            type="warning" position="tr"
            @ok="handleDeleteRecord(record)"
          >
            <a-button size="small" type="text">{{
              baseNameMap.btnAction.label
            }}</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </TableLayout>
    <DetailDrawer v-bind="detailDrawerHandler.bindProps">
      <template #default>
        <a-form
          v-bind="currentItem.bindProps"
          layout="vertical"
          :disabled="detailDrawerHandler.modeIs('detail')"
        >
          <a-form-item
            :field="baseNameMap.itemId.key"
            :label="baseNameMap.formProject.label"
            required
          >
            <a-select
              v-bind="productOptions.bindProps"
              v-model="currentItem.state[baseNameMap.itemId.key]"
              allow-clear
              :placeholder="baseNameMap.formProject.placeholder"
            />
            <!-- <a-input v-model="currentItem.state[baseNameMap.formProject.key]" :placeholder="baseNameMap.formProject.placeholder" /> -->
          </a-form-item>
          <!-- <a-form-item
            :field="baseNameMap.itemUnit.key"
            :label="baseNameMap.itemUnit.label"
            required
          >
            <a-select
              style="color: var(--color-text-1);"
              v-model="currentProject.unitCode"
              :placeholder="baseNameMap.itemUnit.placeholder"
              :options="unitOptions"
              disabled
            />
          </a-form-item> -->
          <a-form-item
            :field="baseNameMap.itemPrice.key"
            :label="baseNameMap.itemPrice.label"
            required
          >
            <a-input-number
              class="m-record-add-price"
              v-model="currentProject.price"
              :min="0" :precision="3" disabled
            >
              <template #append>
                <span>{{ currentProject.unitName? currentProject.unitName:'/' }}</span>
              </template>
            </a-input-number>
          </a-form-item>
          <a-form-item
            :field="baseNameMap.itemYield.key"
            :label="baseNameMap.itemYield.label"
            required
          >
            <a-input-number
              v-model="currentItem.state[baseNameMap.itemYield.key]"
              :min="0"
            >
              <template #append>
                <span>{{ currentProject.unitName }}</span>
              </template>
            </a-input-number>
          </a-form-item>
          <a-form-item
            :field="baseNameMap.itemPerson.key"
            :label="baseNameMap.itemPerson.label"
            required
          >
            <a-input
              v-model="currentItem.state[baseNameMap.itemPerson.key]"
              :placeholder="baseNameMap.itemPerson.placeholder"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :field="baseNameMap.itemPlace.key"
            :label="baseNameMap.itemPlace.label"
            required
          >
            <a-input
              v-model="currentItem.state[baseNameMap.itemPlace.key]"
              :placeholder="baseNameMap.itemPlace.placeholder"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :field="baseNameMap.itemDate.key"
            :label="baseNameMap.itemDate.label"
            required
          >
            <a-date-picker
              v-model="currentItem.state[baseNameMap.itemDate.key]"
              style="width: 100%"
              allow-clear
              :placeholder="baseNameMap.itemDate.placeholder"
            />
          </a-form-item>
        </a-form>
      </template>
    </DetailDrawer>
  </div>
</template>

<style lang="less">
.m-record-add-price {

  & .arco-input-wrapper .arco-input[disabled] {
    color: var(--color-text-1);
    -webkit-text-fill-color: var(--color-text-1);
  }
}
</style>
